(function () {
 
  function fireworks(canvas, ctx) {
    const ballList = [];

    class Ball {
      constructor(x = 200, y = 200, radius = 10, color = 'red') {
        this.x = x;
        this.y = y;
        this.radius = radius;
        this.color = color;
        this.xSpeed = Math.random() * 10 - 5;
        this.ySpeed = Math.random() * 10 - 5;
        this.radiusSpeed = Math.random() + 0.01;
        this.colorSpeed = {
          red: Math.floor(Math.random() * 250),
          yellow: Math.floor(Math.random() * 250),
          blue: Math.floor(Math.random() * 250),
        };
        ballList.push(this);
      }
      render() {
        let { x, y, radius, color } = this;
        ctx.beginPath();
        ctx.fillStyle = color;
        if (radius > 0 && radius < 100) {
          ctx.arc(x, y, radius, 0, Math.PI * 2, false);
        } else {
          ballList.forEach((item, index) => {
            if (item === this) {
              ballList.splice(index, 1);
            }
          });
        }
        ctx.fill();
      }
      update() {
        let { x, y, rSpeed, xSpeed, ySpeed, colorSpeed, radiusSpeed } = this;
        let { red, yellow, blue } = colorSpeed;
        this.x += xSpeed;
        this.y += ySpeed;
        this.radius -= radiusSpeed;
        this.color = `rgba(${red},${yellow},${blue})`;
      }
    }

    let clTime = null;

    canvas.addEventListener('click', function (event) {
      let { offsetX, offsetY } = event;
      for (let i = 0; i < 33; i++) {
        new Ball(offsetX, offsetY);
      }
      clearInterval(clTime);
      clTime = setInterval(() => {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ballList.forEach((item) => {
          item.update();
          item.render();
        });
      }, 1000 / 60);
    });
  }

  let code = {
    name: '动画的简单使用',
    list: [
      {
        name: '烟花',
        width: 500,
        height: 500,
        description: `
        需求：点击屏幕后鼠标会出现向四周扩散的小球

        * 问题：
        *   1.怎么更新小球的位置
        *     解：初始化随机每次小球移动的正负数值
        `,
        demo: fireworks,
      },
    ],
  };

  //初始化函数
  mainData = code;
  watchScriptInit();
})();
